/*
 * Adrian Martinez 11248
 * Maria Fernanda Martinez 11176
 * Rodrigo Mejia 11111
 */
package hoja7;

/**
*Codido de: http://cs.williams.edu/~morgan/code/Splay/
 @file SplayTree.java
 @author Morgan McGuire, morgan@cs.brown.edu
 @created 2002-09-17
 @edited  2002-09-17
 */

public class SplayTree extends BinaryTree implements WordSet {	
	
    /**
     *
     * @param root
     */
    public SplayTree(Node root) {
        super(root);
    }

    //public Node get(int key) {
    public Node getNode(Word word){
        Node node = super.getNode(word);
        splay(node);
        return node;
    }

    public void insert(Node node) {
        super.insert(node);
        splay(node);
    }

    //public void delete(int key) {
    public void delete(Word word){
        delete(super.getNode(word));
    }

    public void delete(Node node) {
        if (node != null) {
            splay(node.parent);
        }
        super.delete(node);
    }

    /**
     *
     * @param node
     */
    public void splay(Node node) {
        if (node == null) {
            return;
        }

        while (! node.isRoot()) {

            // Can't be null-- this isn't the root
            Node p = node.parent;

            // Might be null
            Node g = p.parent;

            if (g == null) {
                // CASE 1: parent but no grandparent
                rotate(node);
                // This will be the last step
                if (! node.isRoot()) {
                    throw new Error("Should have stopped");
                }
            } else {
                
                if (node.isLeft() == p.isLeft()) {
                    // CASE 2: node and parent are both left or right children
                    rotate(p);
                    rotate(node);
                } else {
                    // CASE 3: one of each
                    rotate(node);
                    rotate(node);
                }
            }
        }
    }

	/**
     *
     * @param wordObject
     */
    @Override
	public void add(Word wordObject) {
		// TODO Auto-generated method stub
		insert(new Node(wordObject));
		
	}

	/**
     *
     * @param word
     * @return
     */
    @Override
	public Word get(Word word) {
		
		Node node = root;

        while (node != null) {
        	//if (key == node.key) {
        	if(word.compareTo(node.word) == 0){
                return node.getWord();
            //} else if (key > node.key) {
        	  } else if(word.compareTo(node.word) > 0){	  
                node = node.right;
            //} else if (key < node.key) {
        	  } else if(word.compareTo(node.word) < 0){
                node = node.left;
            }
        }

        return null;
	}
}
